package com.mail.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mail.common.DataResult;
import com.mail.config.MinIoClientConfig;
import com.mail.dto.UserDto;
import com.mail.mapper.UserMapper;
import com.mail.pojo.User;
import com.mail.service.UserService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private MinIoClientConfig minIoClientConfig;

    @Autowired
    private MinioClient minioClient;

    @Resource
    private UserMapper userMapper;

    @Resource
    private PasswordEncoder encoder;


    @Override
    @Transactional
    public DataResult updateUser(Map<String, Object> map) {
        long id = Long.parseLong((String) map.get("id"));
        String username=(String) map.get("username");
        String password=(String) map.get("password");
        String nickname=(String) map.get("nickname");
        String img=(String) map.get("img");
        String status = (String) map.get("status");
        QueryWrapper<User> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("username", username);
        User user1 = userMapper.selectOne(wrapper1);
        if (user1 != null) {
            return DataResult.error("此账号已存在！");
        }
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id);
        wrapper.set(StringUtils.isNotBlank(username), "username", username);
        wrapper.set(StringUtils.isNotBlank(password), "password", encoder.encode(password));
        wrapper.set(StringUtils.isNotBlank(nickname), "nickname", nickname);
        wrapper.set(StringUtils.isNotBlank(img), "img", img);
        wrapper.set(StringUtils.isNotBlank(status), "status", status);
        userMapper.update(null, wrapper);
        return DataResult.success("修改成功！");
    }

    @Override
    @Transactional
    public DataResult UserRegister(UserDto userDto) {
        String username=userDto.getUsername();
        String password=userDto.getPassword();
        String nickname=userDto.getNickname();
        if(StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password) &&StringUtils.isNotBlank(nickname)){
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("username", username);
            User user1 = userMapper.selectOne(wrapper);
            if (user1 != null) {
                return DataResult.error("已存在此用户！");
            }
            String password1=encoder.encode(password);
            User user=new User(username,password1,nickname);
            userMapper.insert(user);

            System.out.println("-------password: "+password1);

            return DataResult.success("注册成功！");
        }else{
            return DataResult.error("请将信息填写完整！");
        }
    }

    @Override
    public DataResult queryUserPage(Map<String, Object> map) {
        int page = Integer.parseInt((String) map.get("page"));
        int limit = Integer.parseInt((String) map.get("limit"));
        String thing=(String) map.get("thing");
        Page<User> pageInfo = new Page<>(page, limit);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.select("id","username","nickname","img","status");
        if (StringUtils.isNotBlank(thing)) {
            wrapper.like("username", thing).or().like("nickname", thing);
        }
        return DataResult.success(userMapper.selectPage(pageInfo,wrapper));
    }

    @Override
    public DataResult getUserById(long id) {
        User user = userMapper.selectById(id);
        if (user != null) {
            return DataResult.success(user);
        } else {
            return DataResult.error("不存在该用户！");
        }
    }

    @Override
    @Transactional
    public DataResult deleteUserById(long id) {
        User user = userMapper.selectById(id);
        if (user != null) {
            userMapper.deleteById(id);
            return DataResult.success("success!");
        } else {
            return DataResult.error("不存在该用户！");
        }
    }

    @Override
    public DataResult queryPasswordByName(String username, String password) {
        User user=userMapper.queryUserIdByUserName(username);
        if(user!=null){
            UpdateWrapper<User> wrapper = new UpdateWrapper<>();
            wrapper.eq("id", user.getId());
            wrapper.set(StringUtils.isNotBlank(password), "password", encoder.encode(password));
            userMapper.update(null, wrapper);
            return DataResult.success("修改成功！");
        }
        return DataResult.error("不存在该用户！");
    }

    @Override
    public DataResult uploadImg(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        String url=minIoClientConfig.getEndpoint();
        String bucketName="test";
        //获取文件名称
        String originalFilename = file.getOriginalFilename();
        //获取文件的类型
        //使用当前时间重新生成文件名，防止文件名称重复造成文件覆盖
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String fileNewName = System.currentTimeMillis() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = sdf.format(d) + "&&" + fileNewName;
        //4.构建文件上传路径
        String filePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //5.文件上传的路径
        String uploadUrl=filePath+"/"+fileName;
        //6.开始上传
        InputStream inputStream=null;
        try {
            inputStream=file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .object(uploadUrl)
                .contentType("image/jpeg")
                .bucket(bucketName)
                .stream(inputStream, inputStream.available(), -1)
                .build();

        minioClient.putObject(putObjectArgs);

        return DataResult.success(url+"/"+bucketName+"/"+uploadUrl);
    }
}
